#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


from datetime import datetime
from ._elempart import ElementPart


class Element:

    def __init__(self, library, etype, esource, eindex, elementIdList):
        assert (esource, eindex) == elementIdList[0]

        self._library = library
        self._etype = etype
        self._esource = esource
        self._eindex = eindex
        self._elementIdList = elementIdList

        self._partDict = None

    @property
    def etype(self):
        return self._etype

    @property
    def esource(self):
        return self._esource

    @property
    def eindex(self):
        return self._eindex

    def get_all_part_names(self):
        self._ensurePartDict()
        return self._partDict.keys()

    def get_parts(self, pnames=None):
        self._ensurePartDict()
        return self._partNamesToPartList(pnames)

    def is_cache_update_needed(self, pnames=None):
        self._ensurePartDict()
        for p in self._partNamesToPartList(pnames):
            if p._dataSrc.is_element_part_cache_need_update(self._etype, p._eindex, p._pname):
                return True
        return False

    def cache(self, pnames=None):
        self._ensurePartDict()
        dt = datetime.now()
        for p in self._partNamesToPartList(pnames):
            p._dataSrc.cache_element_part(self._etype, p._eindex, p._pname, dt)

    def uncache(self):
        self._ensurePartDict()
        for p in self._partNamesToPartList(None):
            for esource, eindex in p._elementIdList:
                self._library._dataSrcDict[esource].uncache_element_part(self._etype, eindex, p.pname)

    def _ensurePartDict(self):
        if self._partDict is not None:
            return

        self._partDict = {}
        try:
            s = " UNION ALL ".join([f"SELECT '{x}' AS esource, '{y}' AS eindex" for x, y in self._elementIdList])
            c = self._library._dbConnDict[self._etype].execute(f'''
                WITH
                    _filter AS (
                        {s}
                    )
                SELECT DISTINCT p.esource, p.eindex, p.pname
                    FROM temp.element_part AS p
                    JOIN temp.datasrc AS d ON p.esource = d.name AND p.db = d.db
                    JOIN _filter AS f ON p.esource = f.esource AND p.eindex = f.eindex
            ''')
            row = c.fetchone()
            while row is not None:
                self._partDict.setdefault(row[2], set()).add((row[0], row[1]))
                row = c.fetchone()

            for pname, elemIdSet in self._partDict.items():
                self._partDict[pname] = ElementPart(self, pname, elemIdSet)
        except BaseException:
            self._partDict = None
            raise

    def _partNamesToPartList(self, pnames):
        if pnames is None:
            return self._partDict.values()
        else:
            return [self._partDict[x] for x in pnames]
